import { Injectable, InternalServerErrorException, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DataSource, Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { Student } from 'src/student/entities/student.entity';
import { Teacher } from 'src/teacher/entities/teacher.entity';
import { UnauthorizedException } from '@nestjs/common';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Student)
    private readonly studentRepository: Repository<Student>, // 新增
    // 新增教师仓库注入
    @InjectRepository(Teacher)
    private readonly teacherRepository: Repository<Teacher>,
    private dataSource: DataSource // 新增事务支持
  ) {}

  async create(createUserDto: CreateUserDto): Promise<User> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();
    console.log('事务启动成功');
  
    try {
      // 根据用户角色分支处理
      if (createUserDto.role === 'teacher') {
        console.log('开始创建教师记录');
        const teacher = this.teacherRepository.create({
          tname: createUserDto.tname,
          tdept: createUserDto.tdept,
          title: createUserDto.title
        });
        
        const savedTeacher = await queryRunner.manager.save(teacher);
        console.log('已保存教师记录:', savedTeacher);

        // 显式重新加载教师记录
        const reloadedTeacher = await queryRunner.manager.findOne(Teacher, {
          where: { tname: createUserDto.tname },
          transaction: true
        });

        if (!reloadedTeacher?.tno) {
          throw new Error('数据库未生成教师编号');
        }
        console.log('生成的教师编号:', reloadedTeacher.tno);

        // 创建用户记录
        const user = this.userRepository.create({
          username: createUserDto.username,
          password: createUserDto.password || '',
          role: createUserDto.role,
          tno: reloadedTeacher.tno,
          sno: '', 
          create_time: new Date()
        });
        const savedUser = await queryRunner.manager.save(user);
        await queryRunner.commitTransaction();
        return savedUser;
      }
      console.log('开始创建学生记录，输入数据:', JSON.stringify(createUserDto));
      
      // 完整的学生实体创建
      const student = this.studentRepository.create({
        sname: createUserDto.sname,
        age: createUserDto.age,
        sex: createUserDto.sex,
        sdept: createUserDto.sdept
      });
      console.log('创建的学生实体:', student);
  
      const savedStudent = await queryRunner.manager.save(student);
      console.log('已保存学生记录:', JSON.stringify(savedStudent));

      // 关键：显式重新加载学生记录
      const reloadedStudent = await queryRunner.manager.findOne(Student, {
        where: { sname: createUserDto.sname },
        transaction: true // 确保在事务中查询
      });

      if (!reloadedStudent?.sno) {
        console.error('错误：数据库触发器未生成学号', savedStudent);
        throw new Error('数据库触发器未成功生成学号');
      }
      console.log('成功生成学号:', reloadedStudent.sno);
  
      console.log('跳过密码加密步骤');  // 新增日志提示
      const plainPassword = createUserDto.password;  // 直接使用原始密码
  
      // 修改学生分支的用户创建逻辑
            const user = this.userRepository.create({
              username: createUserDto.username,
              password: plainPassword,
              role: createUserDto.role,
              sno: reloadedStudent.sno,
              tno: 0,  // 使用数字类型默认值
              create_time: new Date()
            });
      console.log('创建的用户实体:', user);
  
      const savedUser = await queryRunner.manager.save(user);
      console.log('已保存用户记录:', JSON.stringify(savedUser));
      
      await queryRunner.commitTransaction();
      console.log('事务提交成功');
      return savedUser;
    } catch (error) {
      console.error('事务执行失败:', error);
      await queryRunner.rollbackTransaction();
      throw new InternalServerErrorException('用户创建失败: ' + error.message);
    } finally {
      await queryRunner.release();
      console.log('事务连接已释放');
    }
  }

  async findAll(page: number = 1, pageSize: number = 10): Promise<{
    list: User[];
    itemCount: number;
    page: number;
    pageSize: number;
    pageCount: number;
  }> {
    const skip = (page - 1) * pageSize;
    const [data, total] = await this.userRepository.findAndCount({
      skip,
      take: pageSize,
      order: { user_id: 'ASC' },
      // 移除 relations 配置
    });
  
    return {
      list: data,
      itemCount: total,
      page,
      pageSize,
      pageCount: Math.ceil(total / pageSize)
    };
  }

  async findOne(id: number): Promise<User> {
    const user = await this.userRepository.findOneBy({ user_id: id });
    if (!user) {
      throw new NotFoundException(`User with ID ${id} not found`);
    }
    return user;
  }

  async update(id: number, updateUserDto: UpdateUserDto): Promise<User> {
    const user = await this.userRepository.preload({
      user_id: id,
      ...updateUserDto,
    });
    
    if (!user) {
      throw new NotFoundException(`User with ID ${id} not found`);
    }
    
    return this.userRepository.save(user);
  }

  async remove(id: number): Promise<void> {
    const result = await this.userRepository.delete(id);
    if (result.affected === 0) {
      throw new NotFoundException(`User with ID ${id} not found`);
    }
  }

  async login(username: string, password: string): Promise<User> {
    const user = await this.userRepository.findOne({
      where: { username },
      select: ['user_id', 'username', 'password', 'role', 'sno', 'tno']
    });
    
    if (!user || user.password !== password) {
      throw new UnauthorizedException('用户名或密码错误');
    }
    return user;
  }
}